package cn.qianxun.meta.common.core.map;


import cn.qianxun.meta.common.core.utils.StringUtils;

import java.util.*;

/**
 * @Author fuzhilin
 * @Date 2022/8/9 0009 17:05
 * @Description
 */
public class MapSort {

    /**
     * 降序排序
     *
     * @param map
     * @param <K>
     * @param <V>
     * @param num 前几条
     * @return
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map, Integer num) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return -compare;
            }
        });

        Map<K, V> result = new LinkedHashMap<K, V>();
        Integer sort = 1;
        for (Map.Entry<K, V> entry : list) {
            if (StringUtils.isNotNull(num)) {
                // 取出排名前n的值
                if (sort <= num) {
                    result.put(entry.getKey(), entry.getValue());
                    ++sort;
                }else {
                    return result;
                }
            } else {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }


    /**
     * 升序排序
     *
     * @param map
     * @param <K>
     * @param <V>
     * @param num 前几条
     * @return
     */
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueAscending(Map<K, V> map, Integer num) {
        List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
            @Override
            public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
                int compare = (o1.getValue()).compareTo(o2.getValue());
                return compare;
            }
        });
        Map<K, V> result = new LinkedHashMap<K, V>();
        Integer sort = 1;
        for (Map.Entry<K, V> entry : list) {
            if (StringUtils.isNotNull(num)) {
                // 取出排名前n的值
                if (sort <= num) {
                    result.put(entry.getKey(), entry.getValue());
                    ++sort;
                }else {
                    return result;
                }
            } else {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result;
    }

}
